package com.cg.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.cg.entity.User;
import com.cg.mapper.UserMapper;
import com.cg.service.EasyExcelService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * <p>Title: EasyServiceImpl </p>
 * <p>Description: TODO </p>
 * Package: com.cg.service.impl
 * Copyright: Copyright(c) 2020 Hjfruit All Rights Reserved
 * Company: Hjfruit
 * Software: pitaya
 * Date: 2021/5/24 16:05
 *
 * @author cheyinbo
 * @version 1.0.0.0
 */
@Service
@RequiredArgsConstructor
public class EasyExcelServiceImpl implements EasyExcelService {

    private final UserMapper userMapper;

    @Override
    public boolean generateExcel() {
        List<User> users = userMapper.selectList();
        String generatePath = getGeneratePath("chetest.xlsx");
        //生成报表
        generateReport(generatePath,users);
        return users.size() > 0;
    }


    public static void generateReport(String generatePath,Object... object){
        ExcelWriter excelWriter = EasyExcel.write(generatePath).withTemplate(getTemplatePath()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        Arrays.stream(object).forEach(obj -> {
            if (obj instanceof List) excelWriter.fill(obj, fillConfig, writeSheet);
            else excelWriter.fill(obj, writeSheet);
        });
        excelWriter.finish();
    }

    public static InputStream getTemplatePath(){
        return EasyExcelServiceImpl.class.getClassLoader().getResourceAsStream("static/测试.xlsx");
    }

    private static String getGeneratePath(String reportName) {
        File file = new File("C:\\Users\\admin\\Desktop\\che");
        if (!file.exists()) {
            file.mkdirs();
        }
        return new File(file.getAbsolutePath(), reportName).getAbsolutePath();
    }

}
